package com.baibei.ebec.user.mine;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.model.UserInfo;
import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.rae.swift.session.SessionManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UserInfoActivity extends AppCompatActivity {

    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    private static final int PHOTO_CROP = 3;
    @BindView(R2.id.iv_back)
    ImageView ivBack;
    @BindView(R2.id.btn_nickname)
    TextView btnNickname;
    @BindView(R2.id.btn_avatar)
    TextView btnAvatar;
    @BindView(R2.id.tv_nickname)
    TextView tvNickname;
    @BindView(R2.id.iv_avatar)
    RoundedImageView ivAvatar;
    @BindView(R2.id.et_nickname)
    EditText etNickname;
    @BindView(R2.id.tv_save)
    TextView tvSave;
    private File file;
    private String userId;
    private String accessToken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        UserInfo userInfo = SessionManager.getDefault().getUser();
        userId = userInfo.getUserId() + "";

        String userPic = userInfo.getUserPic();
        if (userPic != null) {
            Glide.with(this).load(userPic).into(ivAvatar);
        } else {
            ivAvatar.setImageResource(R.drawable.ic_avatar);
        }
        tvNickname.setText(userInfo.getUserName());

        TokenInfo userToken = SessionManager.getDefault().getUserToken();
        accessToken = userToken.getAccessToken();

    }

    @OnClick(R2.id.iv_back)
    public void onFinishClicked() {
        finish();
    }

    @OnClick(R2.id.btn_nickname)
    public void onNickNameClicked() {
        etNickname.setText(tvNickname.getText());
        tvNickname.setVisibility(View.GONE);
        etNickname.setVisibility(View.VISIBLE);
        etNickname.setFocusable(true);
        etNickname.requestFocus();
        InputMethodManager inputMethodManager = (InputMethodManager) etNickname.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(etNickname,0);

        tvSave.setVisibility(View.VISIBLE);
        btnNickname.setClickable(false);
    }

    @OnClick(R2.id.btn_avatar)
    public void onAvatarClicked() {
        final Dialog dialog = new Dialog(this, 0);
        View view = LayoutInflater.from(this).inflate(R.layout.layout_reset_avatar_dialog, null);
        TextView tvAlbum = view.findViewById(R.id.tv_album);
        TextView tvCamera = view.findViewById(R.id.tv_camera);
        tvAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkWriteAndReadPermissions();
                dialog.dismiss();
            }
        });
        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkCameraPermissions();
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.y = 20;
        window.setAttributes(attributes);
        dialog.show();
    }

    private void checkWriteAndReadPermissions() {
        String[] permissions = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, permissions, 555);
        } else {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, PHOTO_REQUEST);
        }
    }

    private void checkCameraPermissions() {
        String[] permissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, permissions, 666);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(this.getExternalFilesDir("Image").getAbsolutePath(),"avatar.jpg")));
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "avatar.jpg")));
            startActivityForResult(intent, CAMERA_REQUEST);
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 555:
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    checkWriteAndReadPermissions();
                }
                break;
            case 666:
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    checkCameraPermissions();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    private void PhotoClip(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CROP);
    }

    private void toUploadFile() {
        Map<String, File> params = new HashMap<String, File>();//上传map对象
        params.put("pic", file);
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("Content-Type", "multipart/form-data; charset=UTF-8")
                                .build();
                        return chain.proceed(request);
                    }
                }).build();
                RequestBody fileBody = RequestBody.create(MediaType.parse("avatar/jpg"), file);
                MultipartBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("pic", "avatar_img.jpg", fileBody)
                        .addFormDataPart("userId", userId)
                        .addFormDataPart("accessToken", accessToken)
                        .build();
                Request request = new Request.Builder()
                        .url(BuildConfig.API_BASE_URL + "ddq/api/v1/upload/user/pic/byfile")
                        .post(multipartBody)
                        .build();
                Call call = client.newCall(request);
                try {

                    Response execute = call.execute();
                    final JSONObject jsonObject = new JSONObject(execute.body().string());
                    if (!"SUCCESS".equals(jsonObject.optString("code"))) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(jsonObject.optString("message"));
                                return;
                            }
                        });
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setUserPic(jsonObject.optJSONObject("data").optString("userpic"));
                        }
                    });
                } catch (IOException e) {

                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void setUserPic(String string) {
        Glide.with(this).load(string).into(ivAvatar);
        ToastUtils.showShortToast("修改头像成功");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:

                switch (resultCode) {
                    case -1:
//                        File file = new File(Environment.getExternalStorageDirectory(), "avatar.jpg");
                        File file = new File(this.getExternalFilesDir("Image").getAbsoluteFile(), "avatar.jpg");
                        if (file.exists()) {
                            PhotoClip(Uri.fromFile(file));
                        }
                }
                break;
            case PHOTO_REQUEST:
                if (data != null) {
                    Uri uri = data.getData();
                    PhotoClip(uri);
                }
                break;
            case PHOTO_CROP:
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        Bitmap bitmap = bundle.getParcelable("data");
                        try {
//                            String path = Environment.getExternalStorageDirectory().toString();
                            String path = this.getExternalFilesDir("Image").getAbsolutePath();
                            File dirFile = new File(path);
                            if (!dirFile.exists()) {
                                dirFile.mkdir();
                            }
                            File myCaptureFile = new File(path, "avatar.jpg");
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();

                            file = myCaptureFile;
                            toUploadFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
        }
    }

    @OnClick(R2.id.tv_save)
    public void onSaveClicked() {
        if ("".equals(etNickname.getText().toString().trim())){
            ToastUtils.showShortToast("昵称不能为空");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = BuildConfig.API_BASE_URL+"ddq/api/v1/update/user/userName";
                HashMap<String, String> map = new HashMap<>();
                map.put("userName",etNickname.getText().toString());
                map.put("userId",userId);
                map.put("accessToken",accessToken);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    final JSONObject jsonObject = new JSONObject(response.body().string());
                    if (!"SUCCESS".equals(jsonObject.optString("code"))){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(jsonObject.optString("message"));
                            }
                        });
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvNickname.setText(jsonObject.optJSONObject("data").optString("nickname"));
                            etNickname.setText(null);
                            etNickname.setVisibility(View.GONE);
                            tvSave.setVisibility(View.GONE);
                            tvNickname.setVisibility(View.VISIBLE);
                            btnNickname.setClickable(true);
                            ToastUtils.showShortToast("修改昵称成功");
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
